package com.caiyigo.baihua.controller;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import javax.imageio.ImageIO;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.PoolingClientConnectionManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

import com.asprise.util.ocr.OCR;
import com.caiyigo.baihua.dto.Result;
import com.caiyigo.baihua.model.Xuesheng;

public class CjZwUtil {
	public static Result get(Map<String, Xuesheng> xueshengs, String pici,
			boolean isBatch, boolean isZw) throws ClientProtocolException,
			IOException {
		// 线程池
		ExecutorService exe = null;
		// 线程池的容量
		final int POOL_SIZE = 10;
		exe = Executors.newFixedThreadPool(POOL_SIZE);
		HttpParams params = new BasicHttpParams();
		/* 从连接池中取连接的超时时间 */
		ConnManagerParams.setTimeout(params, 2000);
		/* 连接超时 */
		HttpConnectionParams.setConnectionTimeout(params, 4000);
		/* 请求超时 */
		HttpConnectionParams.setSoTimeout(params, 4000);
		SchemeRegistry schemeRegistry = new SchemeRegistry();
		schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory
				.getSocketFactory()));
		PoolingClientConnectionManager cm = new PoolingClientConnectionManager(
				schemeRegistry);
		cm.setMaxTotal(10);
		final HttpClient httpClient = new DefaultHttpClient(cm, params);
		String yzm = getYzm(httpClient);
		while (yzm.length() != 4&& !com.caiyigo.baihua.utils.StringUtils.isNumeric(yzm)) {
			yzm = getYzm(httpClient);
		}
		Map<String,HttpGet> urisToGet = getUrls(xueshengs, pici, yzm.trim(), isBatch,
				isZw);

		// for (HttpGet httpGet : urisToGet) {
		// if (null != httpGet) {
		// exe.execute(new GetThread(httpClient, httpGet, isZw));
		// }
		// }
		List<Future<List<Object>>> resultFutureList = new ArrayList<Future<List<Object>>>();// 存放异步请求的结果

		// 循环请求每个同步服务
		for (String k : urisToGet.keySet()) {
			HttpGet httpGet=urisToGet.get(k);
			
			Future<List<Object>> future = exe.submit(new GetThread(httpClient,
					httpGet, isZw,k.split("_")[0],k.split("_")[1]));
			resultFutureList.add(future);// 将同步结果存放起来
		}
		
		// 遍历同步的的结果
		
		
		exe.shutdown();
		while (!exe.isTerminated()) {// 如果线程池的任务还没有执行完

		}
		System.out.println("Done");
		return new Result(true, resultFutureList);

	}

	// 单独个人获取时，pici值为第一次考试的时间
	public static Map<String,HttpGet> getUrls(Map<String, Xuesheng> xueshengs,
			String pici, String yzm, boolean isBatch, boolean isZw)
			throws UnsupportedEncodingException {
		Map<String,HttpGet> s = new HashMap<String,HttpGet>();
		// HttpGet[] s = new HttpGet[xueshengs.size()];

		if (isBatch) {
			if (isZw) {
				for (String k : xueshengs.keySet()) {
					// http://query.5184.com/query/zk/zk_seat_2014_10.htm
					HttpGet httppost = new HttpGet(
							"http://query.5184.com/query/zk/zk_seat_" + pici.substring(0,4)+"_"+pici.substring(4)
									+ ".jsp?name0=" + k + "&rand=" + yzm
									+ "&serChecked=on");
					s.put(k+"_"+pici,httppost);

				}
			} else {
				for (String k : xueshengs.keySet()) {
					// http://query.5184.com/query/zk/zk_score_201410.jsp?name0=010411201317&rand=1275&serChecked=on
					HttpGet httppost = new HttpGet(
							"http://query.5184.com/query/zk/zk_score_" + pici
									+ ".jsp?name0=" + k + "&rand=" + yzm
									+ "&serChecked=on");
					s.put(k+"_"+pici,httppost);

				}
			}
		} else {
			List<String> piciList = null;
			if (isZw) {
				piciList = buildPici(pici, true);
				for (String k : xueshengs.keySet()) {
					// http://query.5184.com/query/zk/zk_seat_2014_10.htm
					for (String string : piciList) {
						HttpGet httppost = new HttpGet(
								"http://query.5184.com/query/zk/zk_seat_"
										+ string + ".jsp?name0=" + k + "&rand="
										+ yzm + "&serChecked=on");
						s.put(k+"_"+pici,httppost);
					}

				}
			} else {
				piciList = buildPici(pici, false);
				for (String k : xueshengs.keySet()) {
					// http://query.5184.com/query/zk/zk_score_201410.jsp?name0=010411201317&rand=1275&serChecked=on
					for (String string : piciList) {
						HttpGet httppost = new HttpGet(
								"http://query.5184.com/query/zk/zk_score_"
										+ string + ".jsp?name0=" + k + "&rand="
										+ yzm + "&serChecked=on");
						s.put(k+"_"+string,httppost);
					}

				}
			}
		}

		return s;
	}

	public static List<String> buildPici(String beginDate, boolean isZw) {
		List<String> piciList = getPici(beginDate);
		List<String> resultList = new ArrayList<String>();
		for (String string : piciList) {
			if (isZw) {
				resultList.add(string.substring(0, 4) + "_"
						+ string.substring(4));
			} else {
				resultList.add(string.substring(0, 4) + ""
						+ string.substring(4));
			}
		}
		for (String string : resultList) {
			System.out.println(string);
		}
		return resultList;
	}

	public static List<String> getPici(String beginDate) {
		Calendar curCalendar = Calendar.getInstance();
		Calendar a = Calendar.getInstance();
		a.set(Integer.valueOf(beginDate.substring(0, 4)),
				Integer.valueOf(beginDate.substring(4)), 1);
		List<String> piciList = new ArrayList<String>();
		piciList.add(beginDate);

		while (true) {
			if (a.getTime().before(curCalendar.getTime())) {
				a.add(Calendar.MONTH, 3);

				if (String.valueOf(a.get(Calendar.MONTH)).length() < 2) {
					piciList.add(a.get(Calendar.YEAR) + "0"
							+ a.get(Calendar.MONTH));
				} else {
					piciList.add(a.get(Calendar.YEAR) + ""
							+ a.get(Calendar.MONTH));
				}

			} else {
				break;
			}
		}
		return piciList;
	}

	public static String getYzm(HttpClient httpClient)
			throws ClientProtocolException, IOException {

		HttpGet httpget = new HttpGet("http://query.5184.com/query/image.jsp"); // 执行get请求
		HttpResponse response = httpClient.execute(httpget);

		String imgcode = null;
		try {
			imgcode = new OCR().recognizeEverything(ImageIO.read(response
					.getEntity().getContent()));
			// File file = new File("c:/login.jpg");
			// OutputStream ops = new FileOutputStream(file);
			// response.getEntity().writeTo(ops);
			// ops.close();
			// imgcode = new OCR().recognizeEverything(ImageIO.read(file));
			String rand = imgcode.replace("O", "0").replace("i", "1")
					.replace("g", "9").replace("q", "9").replace("G", "9")
					.replace("S", "5").replace("s", "5").replace("B", "8")
					.replace("b", "6").replace("o", "0").replace("l", "1")
					.replace("u", "0").replace("U", "0").replace("Y", "9")
					.trim();
			return rand;
		} catch (Exception e) {

			e.getCause();
			return "1";
		} finally {

		}

	}

}
